package pwd.allen.androiddemo.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.PagerAdapter;
import pwd.allen.androiddemo.R;
import pwd.allen.androiddemo.entity.Planet;
import pwd.allen.androiddemo.util.MethodCommon;

import java.util.ArrayList;
import java.util.List;

/**
 * 和FragmentAdapter相比，需要先全部渲染，避免每次都渲染
 */
public class ImagePagerAdapter extends PagerAdapter {

    private final Context mContext;
    private final List<Planet> list;
    // 声明一个图像视图列表
    private List<View> mViewList = new ArrayList<>();

    public ImagePagerAdapter(Context mContext, List<Planet> list) {
        this.mContext = mContext;
        this.list = list;
        // 给每个商品分配一个专用的图像视图
        for (Planet planet : list) {
            //<editor-fold desc="编码方式">
            //            ImageView view = new ImageView(mContext);
//            view.setLayoutParams(new ViewGroup.LayoutParams(
//                    ViewGroup.LayoutParams.MATCH_PARENT,
//                    MethodCommon.dip2px(mContext, 160)
//            ));
//            view.setScaleType(ImageView.ScaleType.FIT_CENTER);
            //</editor-fold>

            View view = LayoutInflater.from(mContext).inflate(R.layout.fragment_dynamic, null);
            ImageView iv_pic = view.findViewById(R.id.iv_pic);
            TextView tv_desc = view.findViewById(R.id.tv_desc);
            iv_pic.setImageResource(planet.image);
            tv_desc.setText(planet.name);
            mViewList.add(view);
        }
    }

    @Override
    public int getCount() {
        return mViewList.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    // 实例化指定位置的页面，并将其添加到容器中
    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        // 添加一个view到container中，而后返回一个跟这个view可以关联起来的对象，
        // 这个对象能够是view自身，也能够是其余对象，
        // 关键是在isViewFromObject可以将view和这个object关联起来
        View item = mViewList.get(position);
        container.addView(item);
        return item;
    }

    // 从容器中销毁指定位置的页面
    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView(mViewList.get(position));
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return list.get(position).name;
    }
}
